package pub.gll.plugin.asm.task;

import com.android.build.api.transform.Status;

import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

import pub.gll.plugin.asm.annotation.ArchCollectClassVisitor;
import pub.gll.plugin.asm.annotation.ArchInterfaceCheckVisitor;
import pub.gll.plugin.asm.annotation.AspectClassVisitor;
import pub.gll.plugin.util.ClassUtil;
import pub.gll.plugin.util.FileUtil;
import pub.gll.plugin.util.Log;

/**
 * @author: hujianqiang
 * @date: 2021/4/26
 */
public class CollectSrcTask implements Runnable {
    private String TAG = "CollectSrcTask";
    File classFile;
    Status status;

    public CollectSrcTask(File classFile, Status status) {
        this.classFile = classFile;
        this.status = status;
    }

    @Override
    public void run() {
        InputStream is = null;
        try {
            if (ClassUtil.filter(classFile.getAbsolutePath())) {
                is = new FileInputStream(classFile);
                ClassReader classReader = new ClassReader(is);
                ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS);
                classReader.accept(createClassVisitorChain(classWriter, status), 0);
            }
        } catch (Exception e) {
            Log.e(TAG, " Src error : " + e.getMessage());
            e.printStackTrace();
        } finally {
            FileUtil.closeQuietly(is);
        }
    }

    private ClassVisitor createClassVisitorChain(ClassVisitor classVisitor, Status status) {
        ClassVisitor visitor = new AspectClassVisitor(classVisitor);
        ArchInterfaceCheckVisitor checkVisitor = new ArchInterfaceCheckVisitor(Opcodes.ASM7, visitor);
        ClassVisitor archClassVisitor = new ArchCollectClassVisitor(Opcodes.ASM7, checkVisitor, status);
        return archClassVisitor;
    }
}
